#include "linkfabric/StreamBuffer.hpp"
#include <cstddef>

using namespace linkfabric;

void StreamBuffer::addFragment(const TLVFragment& frag) {
    fragments_[frag.seq] = frag;
    if (frag.flags & 0x01) lastReceived_ = true;
}

bool StreamBuffer::isComplete() const {
    if (!lastReceived_) return false;
    auto expected = fragments_.size();
    for (uint16_t i = 0; i < expected; ++i) {
        if (fragments_.count(i) == 0) return false;
    }
    return true;
}

std::vector<uint8_t> StreamBuffer::reassemble() const {
    std::vector<uint8_t> out;
    for (auto& [seq, frag] : fragments_) {
        out.insert(out.end(), frag.value.begin(), frag.value.end());
    }
    return out;
}

std::vector<uint16_t> StreamBuffer::missingSeqs() const {
    std::vector<uint16_t> miss;
    size_t count = fragments_.size();
    for (uint16_t i = 0; i < count; ++i) {
        if (!fragments_.count(i)) miss.push_back(i);
    }
    return miss;
}